import { getCampusSelector } from '@/api/campus/campus'
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import Records from '../Records/index.vue'
export default {
  props: [],
  components: { Records },
  data() {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      MathRandom: 0,
      dataForm: {
        brand: undefined,
        campusId: undefined,
        type: undefined,
        contacts: undefined,
        mobile: undefined,
        acceptTime: undefined,
        assigned: undefined,
        subject: undefined,
        description: undefined,
        source: undefined,
        recordsList: [],
        status: 1,
        fqaId: ''
      },
      dataObj: {
        recordTime: undefined,
        content: undefined,
        statusAfter: undefined,
        connectId: undefined
      },
      recordsVisible: false,
      rules: {
        brand: [
          {
            required: true,
            message: '请输入校区品牌',
            trigger: 'change'
          }
        ],
        campusId: [
          {
            required: true,
            message: '请输入校区名称',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '请输入沟通类型',
            trigger: 'change'
          }
        ],
        contacts: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        subject: [
          {
            required: true,
            message: '请输入沟通主题',
            trigger: 'blur'
          }
        ],
        acceptTime: [
          {
            required: true,
            message: '请输入受理时间',
            trigger: 'change'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入描述',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'blur'
          }
        ],
        assigned: [
          {
            required: true,
            message: '请选择处理人',
            trigger: 'blur'
          }
        ]
      },
      campusOptions: [],
      campusLoading: false,
      brandOptions: [],
      typeOptions: [],
      sourceOptions: [{ fullName: '400', id: '1' }, { fullName: '家校平台', id: '2' }, { fullName: '贝尔校长云', id: '3' }, { fullName: 'VIP群反馈', id: '4' }],
      statusOptions: [{ fullName: '处理中', id: 1 }, { fullName: '已处理', id: 2 }, { fullName: '特殊处理', id: 3 }],
      FQAListAll: []
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'FQAList'])
  },
  watch: {
    'dataForm.brand': {
      async handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          try {
            this.campusLoading = true
            await getCampusSelector({ brand: this.dataForm.brand, fields: 'id,fullName' }).then(res => {
              this.campusOptions = Array.isArray(res.data) ? res.data : []
            })
          } catch (err) {
            console.error('加载校区下拉选项失败:', err)
            this.$message.error('校区选项加载失败')
            this.campusOptions = []
          } finally {
            this.campusLoading = false
          }
        }
      }
    }
  },
  created() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'ConnectType' }).then(res => {
      this.typeOptions = this.isDetail ? res : res.filter(item => item.enabledMark == 1)
    })
  },
  mounted() {},
  methods: {
    getRecordsValue() {
      this.FQAListAll = this.FQAList
    },
    init(id, isDetail) {
      this.$store.dispatch('fqa/setListAll', [])
      this.FQAListAll = []
      this.dataForm.id = id || ''
      this.visible = true
      this.isDetail = isDetail || false
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (this.dataForm.id) {
          request({
            url: '/api/campus/connect/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data
            this.getRecords(this.dataForm.fqaId)
          })
        } else {
          this.dataForm.assigned = this.userInfo.userId
        }
      })
    },
    delRecords(index) {
      this.FQAListAll.splice(index, 1)
      this.$store.dispatch('fqa/setListAll', this.FQAListAll)
    },
    getRecords(ids) {},
    dataFormSubmit() {
      let ids = []
      this.FQAListAll.map(res => {
        ids.push(res.id)
      })
      this.dataForm = Object.assign(this.dataForm, { fqaId: ids.join() })
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (!this.dataForm.id) {
            request({
              url: `/api/campus/connect`,
              method: 'post',
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  ;(this.visible = false), this.$emit('refresh', true)
                }
              })
            })
          } else {
            request({
              url: '/api/campus/connect/' + this.dataForm.id,
              method: 'PUT',
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.visible = false
                  this.$emit('refresh', true)
                }
              })
            })
          }
        }
      })
    },
    addHandle() {
      this.recordsVisible = true
      this.$nextTick(() => {
        this.$refs.RecordsForm.init()
      })
    },
    addHandleRecordsEntityList(row, index) {
      let item = {
        recordTime: undefined,
        content: undefined,
        notes: undefined,
        statusAfter: 1,
        connectId: this.dataForm.id,
        isEdit: false,
        isAdd: true
      }
      this.dataForm.recordsList.push(item)
    },
    deleteRow(index, id) {
      this.dataForm.recordsList.splice(index, 1)
      if (id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          type: 'warning'
        })
          .then(() => {
            request({
              url: `/api/campus/connect/record/${id}`,
              method: 'DELETE'
            }).then(res => {
              this.$message({
                type: 'success',
                message: res.msg,
                onClose: () => {
                  this.init(this.dataForm.id, this.isDetail)
                }
              })
            })
          })
          .catch(() => {})
      }
    },
    //修改取消
    cancel(row) {
      row.isEdit = false
      this.updateTable()
    },
    edit(row) {
      row.isEdit = true
      this.updateTable()
    },
    save(row) {
      row.isEdit = false
      row.isAdd = false
      //保存逻辑
      request({
        url: `/api/campus/connect/record`,
        method: 'post',
        data: row
      }).then(res => {
        this.MathRandom = Math.random()
        this.$message({
          message: res.msg,
          type: 'success',
          duration: 1000,
          onClose: () => {
            this.init(this.dataForm.id, this.isDetail)
          }
        })
      })
      this.updateTable()
    },
    update(row) {
      row.isEdit = false
      this.updateTable()
      //修改逻辑
      request({
        url: `/api/campus/connect/record/${row.id}`,
        method: 'put',
        data: row
      }).then(res => {
        this.MathRandom = Math.random()
        this.$message({
          message: res.msg,
          type: 'success',
          duration: 1000,
          onClose: () => {
            this.init(this.dataForm.id, this.isDetail)
          }
        })
      })
    },
    // 更新表格
    updateTable() {
      this.MathRandom = Math.random()
    }
  }
}
